// pages/mine/myPublish/myPublish.js
const db = wx.cloud.database()
const _ = db.command
const publishDB = db.collection('publishData') //公告数据库
const userinfoDB = db.collection('userInfo')
const app = getApp()
var myInfo = ''

Page({

  currentPage: 1,
  pageSize: 15,
  totalPage:0,

  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    myImg:"",       //用户头像
    myName:"",      //用户昵称
    publishHidden: "",
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    console.log("currentPage", that.currentPage)
    console.log("pageSize", that.pageSize)
    let userimg = app.globalData.head_img
    let username = app.globalData.nickname
    // console.log("userimg", userimg)
    // console.log("username", username)
    that.setData({
      myImg:userimg,
      myName:username
    })
    that.getTotalPage()   //获取总页数
    that.getUserData()    //获取用户信息
    that.getListData()    //获取用户公告
  },

  //获取总页数
  getTotalPage: function () {
    var that = this
    publishDB.where({
      promulgatorID: app.globalData.userOpenid
    }).count().then(res => {
      console.log("counts", res.total)
      let counts = res.total
      that.totalPage = counts === 0 ? 0 : counts <= that.pageSize ? 1 : counts % that.pageSize == 0 ? parseInt(counts / that.pageSize) : parseInt(counts / that.pageSize) + 1
      console.log("totalPage:", that.totalPage)
    })
  },

  //获取公告列表
  getListData: function () {
    var that = this
    publishDB.where({
      promulgatorID: app.globalData.userOpenid
    }).orderBy('publishContent.date', 'desc').orderBy('_id', 'asc')
      .skip((that.currentPage - 1) * that.pageSize)
      .limit(that.pageSize)
      .get({
        success: function (res) {
          // console.log("查询成功", res)
          if (res.data.length == 0) {
            that.setData({
              list:[],
              publishHidden: "你还没有发布公告！"
            })
          } else {
            let index=that.currentPage-1
            that.setData({
              ['list['+index+']']: res.data,
            })
            console.log("list:",that.data.list)
          }
        }, fail: function (res) {
          wx.showToast({
            title: '系统出错',
            icon: "none"
          })
        }
      })
  },

  //获取用户信息
  getUserData: function () {
    userinfoDB.where({
      _openid: app.globalData.userOpenid
    }).get({
      success: function (res) {
        console.log("用户信息", res.data)
        myInfo = res.data
      }, fail: function (res) {
        console.log("查询出错")
      }
    })
  },

  //触底加载
  handlescrollbottom: function () {
    var that = this
    if (that.currentPage >= that.totalPage) {
      wx.showToast({
        title: '亲,没有更多公告了',
        icon: 'none',
        duration: 2000
      })
    } else {
      that.currentPage++
      that.getListData()
    }
  },

  //跳转详情页
  clickNavDetail: function (e) {
    // console.log("公告数据", e.currentTarget.dataset.item)
    let that = this
    let _item = e.currentTarget.dataset.item
    _item['userinfo'] = myInfo
    let item = JSON.stringify(_item)
    // console.log("item",item)
    wx.navigateTo({
      url: '/pages/home/publishDetail/publishDetail?item=' + item
    })
  },

  //点击更多
  clickMore: function (e) {
    console.log("公告ID", e)
    let that = this
    let publishid = e.target.id
    let picArray = e.currentTarget.dataset.picarray
    let deletepub = false
    let delPubsmessage = false
    let delPubReport =false
    wx.showActionSheet({
      itemList: ['删除'],
      success(res) {
        console.log(res.tapIndex)
        if (0 == res.tapIndex) {
          wx.showModal({
            title: '提示',
            content: '你确定要删除这条公告吗？',
            success(res) {
              if (res.confirm) {
                wx.showLoading({
                  title: '删除中',
                })
                publishDB.where({
                  publishID: publishid
                }).remove({
                  success: function (res) {
                    console.log("删除成功", res)
                    wx.cloud.deleteFile({
                      fileList: picArray
                    }).then(res => {
                      // handle success
                      console.log(res.fileList)
                      deletepub = true
                      if (delPubsmessage == true && deletepub == true&&delPubReport==true) {
                        that.delPublishSuccess()
                      }
                    }).catch(error => {
                      // handle error
                    })
                  }, fail: function (res) {
                    wx.showToast({
                      title: '系统错误',
                      icon: "none"
                    })
                  }
                })
                wx.cloud.callFunction({
                  name: 'deleteMessage',
                  data: {
                    publishid: publishid
                  }, success: res => {
                    console.log("删除留言", res)
                    delPubsmessage = true
                    if (delPubsmessage == true && deletepub == true&&delPubReport==true) {
                      that.delPublishSuccess()
                    }
                  },
                  fail: res => {
                    wx.showToast({
                      title: '系统错误',
                      icon: "none"
                    })
                  }
                })
                wx.cloud.callFunction({
                  name:'deleteReport',
                  data:{
                    publishid:publishid
                  },success:res => {
                    console.log("删除举报",res)
                    delPubReport = true
                    if(delPubsmessage == true&&deletepub == true&&delPubReport==true){
                      that.delPublishSuccess()
                    }
                  },
                  fail:res=>{
                    wx.showToast({
                      title: '系统错误',
                      icon:"none"
                    })
                  }
                })
              } else if (res.cancel) {
                console.log('用户点击取消')
              }
            }
          })
        }
      },
      fail(res) {
        console.log(res.errMsg)
      }
    })
  },

  //删除成功
  delPublishSuccess: function () {
    wx.hideLoading();
    wx.showToast({
      title: '删除成功',
      icon: "none"
    })
    this.onLoad()
  },
  previewImage: function (e) {
    app.previewImage(e)
  },
})